package com.hansheng.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hansheng.dao.impl.MaterialDaoImpl;
import com.hansheng.entity.MaterialEntity;
import com.hansheng.service.MaterialService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by GoldenMan on 2017/5/29.
 */
public class MaterialServiceImpl implements MaterialService {

    private MaterialDaoImpl materialDao;

    @Override
    public boolean saveMaterial(MaterialEntity materialEntity) {
        return materialDao.saveMaterial(materialEntity);
    }

    @Override
    public boolean deleteMaterialById(int mid) {
        return materialDao.deleteMaterialById(mid);
    }

    @Override
    @Transactional
    public boolean modifyMaterial(MaterialEntity materialEntity) {
        return materialDao.modifyMaterial(materialEntity);
    }

    @Override
    public JSONArray getMaterialList() {
        List<MaterialEntity> list = materialDao.getMaterialList();
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < list.size(); i++) {
            JSONObject tempJson = new JSONObject();
            tempJson.put("mid", list.get(i).getMid());
            tempJson.put("material", list.get(i).getMaterial());
            tempJson.put("depository", list.get(i).getDepository());
            tempJson.put("fatherMid", list.get(i).getFatherMid());
            jsonArray.add(tempJson);
        }
        return jsonArray;
    }

    @Override
    public JSONArray getFatherMaterialList() {
        String whereHql = "where o.fatherMid is null";
        Object[] params = {};
        List<MaterialEntity> list = materialDao.getFatherMaterialList(whereHql, params);
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < list.size(); i++) {
            JSONObject tempJson = new JSONObject();
            tempJson.put("mid", list.get(i).getMid());
            tempJson.put("material", list.get(i).getMaterial());
            tempJson.put("depository", list.get(i).getDepository());
            tempJson.put("fatherMid", list.get(i).getFatherMid());
            jsonArray.add(tempJson);
        }
        return jsonArray;
    }

    @Override
    public MaterialEntity getMaterialById(int mid) {
        return materialDao.getMaterialById(mid);
    }

    public void setMaterialDao(MaterialDaoImpl materialDao) {
        this.materialDao = materialDao;
    }
}
